package com.talkingdata.hadoop.guard.jsonDemo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.talkingdata.hadoop.guard.bean.User;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ObjectMapper是JSON操作的核心，Jackson的所有JSON操作都是在ObjectMapper中实现。
 * ObjectMapper有多个JSON序列化的方法，可以把JSON字符串保存File、OutputStream等不同的介质中。
 * writeValue(File arg0, Object arg1)把arg1转成json序列，并保存到arg0文件中。
 * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列，并保存到arg0输出流中。
 * writeValueAsBytes(Object arg0)把arg0转成json序列，并把结果输出成字节数组。
 * writeValueAsString(Object arg0)把arg0转成json序列，并把结果输出成字符串。
 */
public class JacksonDemo {
    public static void main(String[] args) throws ParseException, IOException {
        //java2json();
        //json2java();
        //java2json2file();
        //map2json();
        //readjson4file();
        //readjson4file01();
        readjson4file02();
    }
    public static void readjson4file01() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        JsonNode root = objectMapper.readTree(new File("conf/json/namenodestatus.json"));
        JsonNode beans = root.path("beans");
        if (beans.isArray()){
            System.out.println("beans len : " + beans.size());
            for ( JsonNode jsonNode : beans){
                System.out.println("jsonNode : " + jsonNode);
            }
        }
        String s = beans.toString();
    }
    public static void readjson4file02() throws IOException {
        String ss ="{\"LiveNodes\" : \"{\"bj-xg-app-datanode-1001.tendcloud.com:9866\":{\"infoAddr\":\"172.19.1.4:9864\",\"infoSecureAddr\":\"172.19.1.4:0\",\"xferaddr\":\"172.19.1.4:9866\",\"lastContact\":1,\"usedSpace\":428704134254,\"adminState\":\"In Service\",\"nonDfsUsedSpace\":0,\"capacity\":55939987210240,\"numBlocks\":41484,\"version\":\"3.1.0\",\"used\":428704134254,\"remaining\":55511282973393,\"blockScheduled\":2033,\"blockPoolUsed\":428704134254,\"blockPoolUsedPercent\":0.7663644,\"volfails\":0,\"lastBlockReport\":104},\"bj-xg-app-datanode-1002.tendcloud.com:9866\":{\"infoAddr\":\"172.19.1.5:9864\",\"infoSecureAddr\":\"172.19.1.5:0\",\"xferaddr\":\"172.19.1.5:9866\",\"lastContact\":1,\"usedSpace\":428704407374,\"adminState\":\"In Service\",\"nonDfsUsedSpace\":0,\"capacity\":55939987210240,\"numBlocks\":41484,\"version\":\"3.1.0\",\"used\":428704407374,\"remaining\":55511282703904,\"blockScheduled\":2034,\"blockPoolUsed\":428704407374,\"blockPoolUsedPercent\":0.7663648,\"volfails\":0,\"lastBlockReport\":30}}\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap <String,HashMap<String,Object>> s1 = objectMapper.readValue(ss,new TypeReference<HashMap<String,HashMap<String,Object>>>(){});
        for ( HashMap.Entry<String,HashMap<String,Object>> entry : s1.entrySet()){
            System.out.println("key = " + entry.getKey() + "value = " + entry.getValue());
        }
    }
    public static void readjson4file() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(new File("conf/json/user.json"),User.class);
        System.out.println(user.toString());
    }
    public static void map2json() throws IOException {
        Map <String,Object> hashMap = new HashMap<String, Object>();
        hashMap.put("name","zhang");
        hashMap.put("age",1);
        hashMap.put("birthday","1996年09月30日");
        hashMap.put("email","xiaomin@sina.com");
        ObjectMapper mapper = new ObjectMapper();
        String userMap2json = mapper.writeValueAsString(hashMap);
        JsonNode node = mapper.readTree(userMap2json);
        // 输出结果转意，输出正确的信息
        System.out.println(node.get("name").asText());
        // 输出不转意,输出结果会包含""，这是不正确的，除非作为json传递，如果是输出结果值，必须如上一行的操作
        System.out.println(node.get("name"));

        HashMap jsonMap = mapper.readValue(userMap2json,HashMap.class); //转换为HashMap对象
        System.out.println("name : "+jsonMap.get("name"));

    }
    public static void java2json2file() throws ParseException, IOException {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        User user = new User();
        user.setName("小民");
        user.setEmail("xiaomin@sina.com");
        user.setAge(20);
        user.setBirthday(dateformat.parse("1996-10-01"));
        ObjectMapper mapper =  new ObjectMapper();
        //输出格式化后的字符串(有性能损耗)
        mapper.writeValueAsString(user); //返回字符串
        mapper.writeValue(new File("conf/user.json"), user); //指定文件写入
        //设置序列化配置(全局),设置序列化时不输出空值.
    }
    public static void json2java() throws IOException {
        String json = "{\"name\":\"小民\",\"birthday\":\"1996年09月30日\",\"mail\":\"xiaomin@sina.com\"}" ;

        /**
         * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
         */
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user);
    }
    public static void java2json() throws ParseException, JsonProcessingException {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        User user = new User();
        user.setName("小民");
        user.setEmail("xiaomin@sina.com");
        user.setAge(20);
        user.setBirthday(dateformat.parse("1996-10-01"));
        ObjectMapper mapper = new ObjectMapper();
        //User类转JSON
        //输出结果：{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
        String json = mapper.writeValueAsString(user);
        System.out.println(json);

        //Java集合转JSON
        //输出结果：[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
        List<User> users = new ArrayList<User>();
        users.add(user);
        String jsonlist = mapper.writeValueAsString(users);
        System.out.println(jsonlist);
    }
}
